//
//  fensiView.m
//  HappyStore
//
//  Created by 点点充 on 16/1/25.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "fensiView.h"
#define TOPHEIGHT 60
@interface fensiView()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    BOOL nibsRegistered;
}

///@brife 整个视图的大小
@property (assign) CGRect mViewFrame;

///@brife 下方的ScrollView
@property (strong, nonatomic) UIScrollView *scrollView;

///@brife 上方的按钮数组
@property (strong, nonatomic) NSMutableArray *topViews;

///@brife 下方的表格数组
@property (strong, nonatomic) NSMutableArray *scrollTableViews;

///@brife TableViews的数据源
@property (strong, nonatomic) NSMutableArray *dataSource;

///@brife 当前选中页数
@property (assign) NSInteger currentPage;

///@brife 下面滑动的View
@property (strong, nonatomic) UIView *slideView;

///@brife 上方的ScrollView
@property (strong, nonatomic) UIScrollView *topScrollView;

///@brife 上方的view
@property (strong, nonatomic) UIView *topMainView;

@property (strong, nonatomic) NSMutableArray *muArySaveBtn;

@property (assign, nonatomic) NSInteger paggge;

@property (strong, nonatomic) UIViewController *mainVC;

@end
@implementation fensiView
@synthesize paggge;

-(instancetype)initWithFrame:(CGRect)frame WithCount: (NSInteger) count WithVC:(UIViewController *)vc
{
    self = [super initWithFrame:frame];
    
    if (self) {
        _mainVC = vc;
        _mViewFrame = frame;
        _tabCount = count;
        _topViews = [[NSMutableArray alloc] init];
        _scrollTableViews = [[NSMutableArray alloc] init];
        _muArySaveBtn = [NSMutableArray array];
        
        _dataSource = [NSMutableArray array];
        
        
        [self initScrollView];
        
        [self initTopTabs];
        
        [self initDownTables];
        
        
        [self initSlideView];
        
    }
    
    return self;
}


#pragma mark -- 初始化滑动的指示View
-(void) initSlideView{
    
    CGFloat width = _mViewFrame.size.width / 6;
    
    if(self.tabCount <=6){
        width = _mViewFrame.size.width / self.tabCount;
    }
    
    _slideView = [[UIView alloc] initWithFrame:CGRectMake(0, TOPHEIGHT - 15, width, 5)];
    [_slideView setBackgroundColor:[UIColor colorWithRed:32/255.f green:165/255.f blue:240/255.f alpha:1.f]];
    [_topScrollView addSubview:_slideView];
}


#pragma mark -- 实例化ScrollView
-(void) initScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _mViewFrame.origin.y, _mViewFrame.size.width, _mViewFrame.size.height - TOPHEIGHT)];
    _scrollView.contentSize = CGSizeMake(_mViewFrame.size.width * _tabCount, _mViewFrame.size.height - 60);
    _scrollView.backgroundColor = [UIColor whiteColor];
    
    _scrollView.pagingEnabled = YES;
    
    _scrollView.delegate = self;
    [self addSubview:_scrollView];
}



#pragma mark -- 实例化顶部的tab
-(void) initTopTabs{
    CGFloat width = _mViewFrame.size.width / 6;
    
    if(self.tabCount <=6){
        width = _mViewFrame.size.width / self.tabCount;
    }
    
    _topMainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _mViewFrame.size.width, TOPHEIGHT)];
    
    _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _mViewFrame.size.width, TOPHEIGHT)];
    
    _topScrollView.showsHorizontalScrollIndicator = NO;
    
    _topScrollView.showsVerticalScrollIndicator = YES;
    
    _topScrollView.delegate = self;
    
    
    _topScrollView.contentSize = CGSizeMake(width * _tabCount, TOPHEIGHT);
    [self addSubview:_topMainView];
    
    [_topMainView addSubview:_topScrollView];
    
    UIView *viewBack = [[UIView alloc] initWithFrame:(CGRect){0,TOPHEIGHT-10,320,10}];
    viewBack.backgroundColor = [UIColor colorWithWhite:0.8f alpha:1.f];
    [_topMainView addSubview:viewBack];
    
    
    
    NSArray *aryTitle = @[@"个人",@"企业",@"政府"];
    
    for (int i = 0; i < _tabCount; i ++) {
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 0, width, TOPHEIGHT)];
        button.tag = i;
        [button setTitle:aryTitle[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(tabButton:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor colorWithRed:89/255.f green:87/255.f blue:87/255.f alpha:1.f] forState:UIControlStateNormal];
        
        [_muArySaveBtn addObject:button];
        [_topViews addObject:button];
        [_topScrollView addSubview:button];
    }
}



#pragma mark --点击顶部的按钮所触发的方法
-(void) tabButton: (UIButton *) sender
{
    _currentPage = sender.tag;
    [self updateTableWithPageNumber:_currentPage];
    //顶部跟着滑动
    [_topScrollView scrollRectToVisible:CGRectMake(sender.frame.origin.x-sender.frame.size.width*2, 0, _topScrollView.frame.size.width, _topScrollView.frame.size.height) animated:YES];
    [_scrollView setContentOffset:CGPointMake(sender.tag * _mViewFrame.size.width, 0) animated:YES];
}

#pragma mark --初始化下方的TableViews
-(void) initDownTables{
    
    for (int i = 0; i < 2; i ++) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(i * _mViewFrame.size.width, 0, _mViewFrame.size.width, _mViewFrame.size.height - TOPHEIGHT - 64)];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tag = i;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            paggge = 1;
            [self startSearch];
        }];
        
        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            paggge += 1;
            [self startSearch];
        }];
        
        tableView.mj_footer.hidden = YES;
        
        if (i == 0) {
            // 马上进入刷新状态
            [tableView.mj_header beginRefreshing];
        }
        
        [_scrollTableViews addObject:tableView];
        [_scrollView addSubview:tableView];
    }
    
}


#pragma mark --根据scrollView的滚动位置复用tableView，减少内存开支
-(void) updateTableWithPageNumber: (NSUInteger) pageNumber{
    int tabviewTag = pageNumber % 2;
    
    CGRect tableNewFrame = CGRectMake(pageNumber * _mViewFrame.size.width, 0, _mViewFrame.size.width, _mViewFrame.size.height - TOPHEIGHT - 64);
    
    UITableView *reuseTableView = _scrollTableViews[tabviewTag];
    reuseTableView.frame = tableNewFrame;
    
    // 马上进入刷新状态
    [reuseTableView.mj_header beginRefreshing];
}




#pragma mark -- scrollView的代理方法

-(void) modifyTopScrollViewPositiong: (UIScrollView *) scrollView{
    
    if (scrollView == _scrollView) {
        UIButton *sender = _muArySaveBtn[_currentPage];
        //顶部跟着滑动
        [_topScrollView scrollRectToVisible:CGRectMake(sender.frame.origin.x-sender.frame.size.width*2, 0, _topScrollView.frame.size.width, _topScrollView.frame.size.height) animated:YES];
    }
    
}

///拖拽后调用的方法
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self modifyTopScrollViewPositiong:scrollView];
}



-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    //    [self scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:_scrollView]) {
        _currentPage = _scrollView.contentOffset.x/_mViewFrame.size.width;
        
        _currentPage = _scrollView.contentOffset.x/_mViewFrame.size.width;
        
        //    UITableView *currentTable = _scrollTableViews[_currentPage];
        //    [currentTable reloadData];
        
        [self updateTableWithPageNumber:_currentPage];
        
        return;
    }
    //顶部跟着动
    [self modifyTopScrollViewPositiong:scrollView];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([_scrollView isEqual:scrollView]) {
        CGRect frame = _slideView.frame;
        
        if (self.tabCount <= 6) {
            frame.origin.x = scrollView.contentOffset.x/_tabCount;
        } else {
            frame.origin.x = scrollView.contentOffset.x/6;
            
        }
        
        
        _slideView.frame = frame;
    }
    
}





#pragma mark -- talbeView的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:_dataSource.count];
    return _dataSource.count;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_currentPage < 3) {//个人信息
        return 90;
    }else if (_currentPage == 6) {//招聘
        return 120;
    }else {
        return 110;
    }
}

-(UITableViewCell *)tableView:tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cell1 = @"cell1";
    
    
    BOOL nibsRegistered1 = NO;
    if (!nibsRegistered1) {
        UINib *nib=[UINib nibWithNibName:@"TableViewCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cell1];
        nibsRegistered1 = YES;
    }
    
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell1];
    
    UIImageView *imgV = [cell viewWithTag:10];
    [imgV sd_setImageWithURL:[NSURL URLWithString:_dataSource[indexPath.row][@"headPhoto"]] placeholderImage:[UIImage imageNamed:@"project_detail_heder_normal"]];
    imgV.layer.masksToBounds = YES;
    imgV.layer.cornerRadius = 25.f;
    
    UILabel *labPeople = [cell viewWithTag:11];
    if (_dataSource[indexPath.row][@"userName"] == [NSNull null] || [_dataSource[indexPath.row][@"userName"] isEqualToString:@"null"]) {
        labPeople.text = _dataSource[indexPath.row][@"account"];
    }else {
        labPeople.text = [NSString stringWithFormat:@"%@(%@)",_dataSource[indexPath.row][@"userName"],_dataSource[indexPath.row][@"account"]];
    }
    
    //职位
    UILabel *labPositionName = [cell viewWithTag:12];
    //positionName-
    //goveAccount 政府账户
    //companyAccount 企业帐户
    
    NSMutableString *muStr = [NSMutableString string];
    if (_dataSource[indexPath.row][@"positionName"] == [NSNull null] || [_dataSource[indexPath.row][@"positionName"] isEqualToString:@"null"]) {
        
    }else {
        [muStr appendFormat:@"%@-",_dataSource[indexPath.row][@"positionName"]];
        
    }
    
    BOOL isNull = NO;
    if (_dataSource[indexPath.row][@"companyAccount"] == [NSNull null] || [_dataSource[indexPath.row][@"companyAccount"] isEqualToString:@"null"]) {
        if (_dataSource[indexPath.row][@"companyUserName"] == [NSNull null] || [_dataSource[indexPath.row][@"companyUserName"] isEqualToString:@"null"] ) {
            isNull = YES;
        }
        
    }else {
        if (_dataSource[indexPath.row][@"companyUserName"] == [NSNull null] || [_dataSource[indexPath.row][@"companyUserName"] isEqualToString:@"null"]) {
            [muStr appendFormat:@"%@",_dataSource[indexPath.row][@"companyAccount"]];
        }else {
            [muStr appendFormat:@"%@",_dataSource[indexPath.row][@"companyUserName"]];
        }
        
    }
    
    
    if (_dataSource[indexPath.row][@"goveAccount"] == [NSNull null] || [_dataSource[indexPath.row][@"goveAccount"] isEqualToString:@"null"]) {
        if (_dataSource[indexPath.row][@"goveUserName"] == [NSNull null] || [_dataSource[indexPath.row][@"goveUserName"] isEqualToString:@"null"]) {
            if (isNull) {
                [muStr appendString:@"无"];
            }
            
        }
        
    }else {
        if (_dataSource[indexPath.row][@"goveUserName"] == [NSNull null] || [_dataSource[indexPath.row][@"goveUserName"] isEqualToString:@"null"]) {
            [muStr appendFormat:@"%@",_dataSource[indexPath.row][@"goveAccount"]];
        }else {
            [muStr appendFormat:@"%@",_dataSource[indexPath.row][@"goveUserName"]];
        }
        
    }
    
    labPositionName.text = muStr;
    
    
    UILabel *labAddress = [cell viewWithTag:13];
    if (_dataSource[indexPath.row][@"address"] == [NSNull null] || [_dataSource[indexPath.row][@"address"] isEqualToString:@"null"]) {
        labAddress.text = @"无";
    }else {
        labAddress.text = _dataSource[indexPath.row][@"address"];
    }
    
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    _mainVC.navigationItem.backBarButtonItem = barButtonItem;
    
    switch (_currentPage) {
        case 0://个人
        {
            ThirdPerson_Person *person = [self.mainVC.storyboard instantiateViewControllerWithIdentifier:@"thirdPerson"];
            person.strUserId = _dataSource[indexPath.row][@"userId"];
            person.strUserType = @"1";//个人
            person.strUserName = [NSString stringWithFormat:@"%@的详情",_dataSource[indexPath.row][@"userName"]];
            [self.mainVC.navigationController pushViewController:person animated:YES];
        }
            break;
        case 1://企业
        {
            ThirdPerson_Company *person = [self.mainVC.storyboard instantiateViewControllerWithIdentifier:@"thirdCompany"];
            person.strUserId = _dataSource[indexPath.row][@"userId"];
            person.strUserType = @"2";//企业
            person.strUserName = [NSString stringWithFormat:@"%@的详情",_dataSource[indexPath.row][@"userName"]];
            [self.mainVC.navigationController pushViewController:person animated:YES];
        }
            break;
        case 2://政府
        {
            ThirdPerson_Government *person = [self.mainVC.storyboard instantiateViewControllerWithIdentifier:@"thirdGovernmet"];
            person.strUserId = _dataSource[indexPath.row][@"userId"];
            person.strUserType = @"3";//企业
            person.strUserName = [NSString stringWithFormat:@"%@的详情",_dataSource[indexPath.row][@"userName"]];
            [self.mainVC.navigationController pushViewController:person animated:YES];
        }
            break;
    }
    
}



- (void)startSearch
{
    [self showRoundProgressWithTitle:@"加载中..."];
    //token=验证用户&page=页码&userId=用户id
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
    [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];
    
    NSString *strURl = @"";
    switch (_currentPage) {
        case 0://个人
        {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getFocus_People_My_app_focus.im.lensum"];
        }
            break;
        case 1://企业
        {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getFocus_Comamy_My_app_focus.im.lensum"];
        }
            break;
        case 2://政府
        {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getFocus_Gove_My_app_focus.im.lensum"];
        }
            break;
    }
    
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        UITableView *_mainTableView = _scrollTableViews[_currentPage%2];
        [_mainTableView.mj_header endRefreshing];
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//        NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            [_mainTableView.mj_header endRefreshing];
            if (paggge == 1) {
                _dataSource = [NSMutableArray arrayWithArray:[dicInfo objectForKey:@"data"][@"record"]];
                
                if (_dataSource.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }else {
                NSArray *ary11 = [dicInfo objectForKey:@"data"][@"record"];
                for (int i = 0; i<ary11.count; i++) {
                    NSDictionary *dic1 = ary11[i];
                    [_dataSource addObject:dic1];
                }
                if (ary11.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }
            
            
            [_mainTableView reloadData];
            [self hideBubble];
        }else {
            if (paggge == 1) {
                _dataSource = [NSMutableArray array];
            }
            
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];

        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        UITableView *_mainTableView = _scrollTableViews[_currentPage%2];
        [_mainTableView.mj_header endRefreshing];
        [_mainTableView.mj_footer endRefreshing];
        if (paggge == 1) {
            _dataSource = [NSMutableArray array];
            [_mainTableView reloadData];
        }

        [self showSingleIconBubble:error.localizedDescription];

    }];
}




@end
